package com.atguigu.yygh.host.api.API;

import com.atguigu.yygh.common.Result;
import com.atguigu.yygh.common.config.YyghException;
import com.atguigu.yygh.host.service.HospitalService;
import com.atguigu.yygh.host.service.HospitalSetService;
import com.atguigu.yygh.host.utils.HttpRequestHelper;
import com.atguigu.yygh.host.utils.MD5;
import com.atguigu.yygh.model.hosp.Hospital;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author DongYu Zhou
 * @date 2022/6/24 17:18
 */
@Api(tags = "医院管理API接口")
@RestController
@RequestMapping("/api/hosp")
public class APIHospitalController {

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private HospitalSetService hospitalSetService;

    @ApiOperation(value = "保存医院信息")
    @PostMapping("/saveHospital")
    public Result<Hospital> saveHospital(HttpServletRequest request){
        // 1.获取数据
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> stringObjectMap = HttpRequestHelper.switchMap(parameterMap);
        // 签名校验
        String hoscode = (String) stringObjectMap.get("hoscode");
        String sign = (String) stringObjectMap.get("sign");
        //获取医院签名
       String hospSign = hospitalSetService.getHoscSign(hoscode);
        String hospSignMD5 = MD5.encrypt(hospSign);
        //对比
        System.out.println("hospSignMD5 = " + hospSignMD5);
        System.out.println("sign = " + sign);
        if (!hospSignMD5.equals(sign)){
            throw new YyghException(20001, "签名错误");
        }

        //传输过程中“+”转换为了“ ”，因此我们要转换回来
        String logoData = (String)stringObjectMap.get("logoData");
        logoData = logoData.replaceAll(" ","+");
        stringObjectMap.put("logoData",logoData);

        //保存数据
        hospitalService.saveHospital(stringObjectMap);
        return Result.ok();
    }

    @ApiOperation(value = "查询医院信息")
    @PostMapping("hospital/show")
    public Result<Hospital> hospitalShow(HttpServletRequest request){
        // 1.获取数据
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> stringObjectMap = HttpRequestHelper.switchMap(parameterMap);
// 签名校验省略
        String hoscode = (String) stringObjectMap.get("hoscode");
        String sign = (String) stringObjectMap.get("sign");
        //3.查询
       Hospital hospital= hospitalService.hospitalShow(hoscode);

       return Result.ok(hospital);

    }

}
